package cn.icanci.loopstack.rec.engine.script.wrapper;

import cn.hutool.json.JSONUtil;

import java.util.Map;
import java.util.StringJoiner;

import com.google.common.collect.Maps;

/**
 * Http请求结果Wrapper
 *
 * @author icanci
 * @since 1.0 Created in 2022/11/14 22:36
 */
public class HttpResponseWrapper {
    /**
     * 执行结果
     */
    private String    response;
    /**
     * 执行异常
     */
    private Throwable exception;

    /**
     * 判断返回是否是JSON
     * 
     * @return 判断返回是否是JSON
     */
    public boolean isJson() {
        return JSONUtil.isJson(response);
    }

    /**
     * 获取返回结果的Map
     *
     * @return 返回Map
     */
    public Map<String, Object> getResponseForMap() {
        if (response == null) {
            return Maps.newHashMap();
        }
        return JSONUtil.toBean(response, Map.class);
    }

    /**
     * 是否执行成功
     *
     * @return 返回是否执行成功
     */
    public boolean isSuccess() {
        return response != null || exception == null;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }

    public Throwable getException() {
        return exception;
    }

    public void setException(Throwable exception) {
        this.exception = exception;
    }

    @Override
    public String toString() {
        return new StringJoiner(",").add("response=" + response).add("exception=" + exception).toString();
    }

}
